﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RecipeBookBusiness
{
    public class Equipment
    {
        private RecipeBookEntities _entities = new RecipeBookEntities();
        private int _id;
        private string _description;

        public Equipment(int equipID)
        {
            loadEquipmentClass(equipID);
        }

        public Equipment(string description)
        {
            try
            {
                EquipmentDataRow edr = new EquipmentDataRow();
                edr.Description = description;

                //Save to DB and get ID
                _entities.AddToEquipmentDataRowSet(edr);
                _entities.SaveChanges();
                int newEquipmentID = 0;
                foreach (EquipmentDataRow idEdr in _entities.EquipmentDataRowSet)
                {
                    if (idEdr.ID > newEquipmentID)
                        newEquipmentID = idEdr.ID;
                }
                loadEquipmentClass(newEquipmentID);
            }
            catch (Exception ex)
            {
                //TODO: Real exception handling
                Console.Write(ex.Message);
            }
        }

        public void UpdateEquipment(string description)
        {
            EquipmentDataRow equipmentDR = (from c in _entities.EquipmentDataRowSet
                                          where c.ID == _id
                                          select c).FirstOrDefault();
            bool needToUpdate = false;
            if (!_description.Equals(description))
            {
                _description = description;
                needToUpdate = true;
            }

            if (needToUpdate)
            {
                equipmentDR.Description = _description;
                _entities.SaveChanges();
            }
        }

        public void DeleteEquipment()
        {
            EquipmentDataRow edr = (from c in _entities.EquipmentDataRowSet
                                 where c.ID == _id
                                 select c).FirstOrDefault();
            _entities.DeleteObject(edr);
            _entities.SaveChanges();
        }

        private void loadEquipmentClass(int equipID)
        {
            EquipmentDataRow equipmentDR = (from c in _entities.EquipmentDataRowSet
                                            where c.ID == equipID
                                            select c).FirstOrDefault();
            _id = equipmentDR.ID;
            _description = equipmentDR.Description;
        }

        public int ID
        {
            get
            {
                return _id;
            }
        }

        public string Description
        {
            get
            {
                return _description;
            }
        }
    }
}
